#include "TelephoneBook.h"
#include <stdio.h>
#include <string.h>

_t_info a[100];
void _init_telephone_book(_t_book *book)
{
    book->size = 0;
}

void _insert_telephone_book(_t_book *book)
{
    if (book->size == Size)
    {
        printf("通讯录已满！\n\n");
        return;
    }
    else
        printf("请输入所需添加的联系人：");
    scanf("%s", book->info[book->size].name.str);
        printf("请输入号码：");
    scanf("%s", book->info[book->size].num.str);
    book->size++;
    printf("添加成功！\n\n");  
}

void _search_telephone_book(_t_book *book)
{
    if(book->size == 0)
    {
        printf("通讯录为空！\n");
        return;
    }
    printf("请输入需要查询的联系人：");
    char Name[Size];
    scanf("%s", Name);
    int i;
    for (i = 0; i < book->size; i++)
    {
        if (strcmp(book->info[i].name.str, Name) == 0)
        {
            printf("联系人: %s    电话: %s\n", book->info[i].name.str, book->info[i].num.str);
        }
        if (strcmp(book->info[i].name.str, Name) != 0)
        {
            printf("查无此人！\n");
            break;
        }
        
    }
}

void _rm_by_index(_t_book *book, int index)
{
    for(int i = index; i < book->size - 1; i++)
    {
        book->info[i] = book->info[i+1];
    }
    book->size--;
}

void _delete_telephone_book(_t_book *book)
{
    printf("请输入需要删除联系人的电话号码：");
    char Number[Size];
    scanf("%s",Number);
    int flag = 0;
    for (int i = 0; i < book->size; i++)
    {
        if (strcmp(book->info[i].num.str, Number) == 0)
        {
            _rm_by_index(book, i);
            i--;
            flag = 1;     
        }
        else
            printf("未找到该联系人！\n");
    }
    if(flag == 1)
    {
        flag = 0;
        printf("联系人删除成功！\n");
        return;
    }
}

void _update_telephone_book(_t_book *book, const char *old_phone_number)
{
    _my_str newphone;
    _init_my_string(&newphone);

    printf("输入新的电话号码:");
    scanf("%s", newphone.str);

    int i;
    for (i = 0; i < book->size; i++)
    {
        if (strcmp(book->info[i].num.str, old_phone_number) == 0)
        {
            strcpy(book->info[i].num.str, newphone.str);
            printf("电话号码更新成功！\n");
        }
        else
        {
            printf("未找到该联系人！\n");
        }
    }
}
